package com.zxw.mallafter.common;


import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    private String secret;

    public JwtInterceptor(String secret) {
        this.secret = secret;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {
        //从客户端获取token
        String jwt = request.getHeader("jwt");
        //解密
        try {
            DecodedJWT decode = JwtUtils.decode(jwt, secret);
        //成功放行
            return true;
        } catch (Exception e) {
            Tojson.writeJson(resp, Map.of("code", 401, "error", "未登录"));

            return false;
        }
    }
}
